import { LogMode } from "node-windows";

<template name="home" class="home">
  <view>
    <view id="container" class="container"></view>
    <!-- 消息提醒 -->
    <div class="notification" @tap="getMsgList">
      <div v-if="messageNum !== 0" class="heartbeat">{{ messageNum }}</div>
      <div
        v-else
        :style="{ backgroundColor: SiteNum == 0 ? '#999' : '#4095e5' }"
        class="messageNum"
      >
        {{ messageNum }}
      </div>
      <!-- <div class="message">New Message!</div> -->
    </div>
    <div class="device_box" v-show="SiteNum == 0">雷达设备暂未连接!</div>
    <!-- 控件 -->
    <div class="contron_box">
      <div
        v-for="item in control_list"
        :key="item.index"
        class="c_items"
        @tap="getControl(item)"
      >
        <view style="font-size: 16px" :class="['cuIcon-' + item.cuIcon]"></view>
        <p>{{ item.name }}</p>
      </div>
    </div>
    <!-- 弹窗 -->
    <Modal
      @handCheck="handCheck"
      :modalName="modalName"
      :modalData="modalData"
      :title="title"
      @hideModal="hideModal"
      @changeMap="changeMap"
      @handleSetMap="handleSetMap"
      :showFlag="showFlag"
      :radarIP="radarIP"
      :centerPoint="centerPoint"
      :radarName="radarName"
    >
      <template v-slot:markers>
        <tr
          v-for="(item, index) in processedMarkers"
          :key="index"
          :class="item.BatchNumber === markerId ? 'active' : ''"
          @click="handleDoubleClick(item)"
        >
          <td v-if="item.BatchNumber">{{ item.BatchNumber }}</td>
          <td v-if="item.Type">{{ getType(item.Type) }}</td>
          <td v-if="item.Distance">{{ Number(item.Distance).toFixed(2) }}</td>
          <td v-if="item.Azimuth">{{ Number(item.Azimuth).toFixed(2) }}</td>
          <td v-if="item.Amplitude">{{ item.Amplitude }}</td>
          <td v-if="item.RadialVelocity">
            {{ Number(item.RadialVelocity).toFixed(2) }}
          </td>
          <td v-if="item.Longitude">{{ Number(item.Longitude).toFixed(2) }}</td>
          <td v-if="item.Latitude">{{ Number(item.Latitude).toFixed(2) }}</td>

          <td v-if="item.Altitude">{{ Number(item.Altitude).toFixed(2) }}</td>
          <td v-if="item.Time">{{ getDateString(item.Time) }}</td>
          <td v-if="item.Course">{{ Number(item.Course).toFixed(2) }}</td>
          <td v-if="item.Elevation">{{ Number(item.Elevation).toFixed(2) }}</td>
          <td v-if="item.Noise">{{ Number(item.Noise).toFixed(2) }}</td>
          <td v-if="item.Speed">
            {{ Number(item.Speed).toFixed(2) }}
          </td>
        </tr>
      </template>
    </Modal>
  </view>
</template>

<script module="" lang="renderjs">
 	import socket from "@/common/js-sdk/socket/socket.js";
	import Modal from './modal.vue'

	export default {
	name: "home",
	components: {
		Modal
	},
data() {
	return {
		radarIP:'192.168.0.182',
		radarName:'雷达1',
		showp:false,
		modalName:'',
		title:'',
		control_list:[
			{
			name:'图层',
			cuIcon:'favorfill'
			},{
				name:'站点',
				cuIcon:'locationfill'
			},{
				name:'刷新',
				cuIcon:'selectionfill'
			},{
				name:'列表',
				cuIcon:'commentfill'
			},{
				name:'设置',
				cuIcon:'settingsfill'
			}
		],
		messageNum:0,
		marker: {},
		polylines:[],
		Polyline:null,
		socketTask: null, // socket实例
		socketOpen: false, // socket是否连接
		reconnectTimer: null, // 重连计时器
		reconnectNum: 2, // 重连次数
		reconnectDelay: 3000, // 重连间隔
		mapData:null,
		SiteNum:0,
		info:{},
		ids:[],
		markers:[],
		processedMarkers:[],
		map: {},
		polyline: {},
		path:[],
		polylinePath:[],
		modalData:[],
		markerId:null,
		isMoving:false,
		showFlag:null,
		circles:[],
		circleList:['500','3000','5000'],
		showPosition:false,
		showpId:true,
		showDuFenMiao:false,
		AMap: null,
		webSocketTask:null,
		token:null,
		infoWindow:null,
		centerMarker1:null,
		centerPoint:[114.456924,30.448900],
		createdMarkers:[],
		textLable:null,
		msgFlag:true, // 用来判断是直接点击目标marker 还是在列表点的
		showList:{
			BatchNumber:'',
			Type:'',
			Distance:'',
			Azimuth:'',
			Amplitude:'',
			RadialVelocity:'',
			Longitude:'',
			Latitude:'',
		},
	}
},
watch:{
	centerPoint(newVal){
		if(newVal && this.map){
			this.map.setCenter(newVal)
			this.centerMarker1.setPosition(newVal)
			if (this.circles && this.circles.length > 0) {
			this.circles.forEach(circle => {
				circle.setCenter(newVal);
			});
		}
		}
	},
	circleList(newVal,oldVal){
		let arrList=newVal?newVal:this.circleList
		if(this.map){
			const _this =this
			const center = this.centerPoint
			// 清除之前的刻度
			_this.clearMapCircles();
			// 添加新刻度
			arrList.forEach(item => {
				// setTimeout(()=>{
				var circle = new AMap.Circle({
					map: _this.map,
					center:  center , // 圆心位置
					radius: item, // 半径 单位:米
					strokeColor: "#1a61d3", // 线颜色
					strokeOpacity: 1, // 线透明度
					strokeWeight: 2, // 线粗细度
					fillColor: "#d3e3fd", // 填充颜色
					fillOpacity: 0.1, // 填充透明度
				});

				// 将新刻度保存到数组中，以便后续清除
				_this.circles.push(circle);
				// },200)
				// _this.map.setFitView();
			});


		}
	},

},
 created(){
	this.token = uni.getStorageSync('Access-Token') || null
	this.showPosition = uni.getStorageSync('showPosition')? uni.getStorageSync('showPosition'):this.showPosition
	this.showpId = uni.getStorageSync('pId')? uni.getStorageSync('pId'):this.showpId
	this.showDuFenMiao = uni.getStorageSync('lData')? uni.getStorageSync('lData'):this.showDuFenMiao
	this.radarName = uni.getStorageSync('radarName') || '雷达1'
    this.radarIP = uni.getStorageSync('radarIP') || '192.168.0.182'
	// 查询雷达的相关信息
	this.getDerviceMsg()
},
mounted() {
	const A_MAP_KEY = "1f520f629a5d77331f39101e3ba2ca7e"; // 地图key
	const A_MAP_SECRET_KEY = "1bdb81bea11b57789cb8954098488ba0"; // 地图密钥
	// 地图初始化
	const script = document.createElement('script');
	script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${A_MAP_KEY}`;
	script.onload = this.initAmap.bind(this);
	document.head.appendChild(script);
	const script1 = document.createElement('script');
	script1.src = '../../map.js';
	script1.onload = this.initAmap.bind(this);
	document.head.appendChild(script1);
	setTimeout(() => {
		this.circleList = uni.getStorageSync('circle')?JSON.parse(uni.getStorageSync('circle')):this.circleList
		this.circleList.push('0')
	}, 500);
	//获取浏览器缓存数据的方法
	// this.getMapDataFromCache()
	this.initSocket();
},
unmounted() {
	this.map?.destroy();
},
methods: {
	// 点击列表 展示当前点击的id 对应的marker的实时信息
	handleDoubleClick(item){
		const pos =  this.WGS84_2_GCJ02( [item.Longitude, item.Latitude])
		this.map.setCenter(pos);
		const _this = this;
	 // 遍历标记数组，找到与点击的相关的标记，并添加移动事件监听器
		for (let i = 0; i < this.markers.length; i++) {
			if (this.markers[i].w.id === item.BatchNumber) {
				const marker = this.markers[i];
				// 手动触发标记的点击事件
				_this.msgFlag = false
				AMap.event.trigger(marker, 'click');
			}
		}
		_this.msgFlag = true
	},
	// 84坐标转换
	WGS84_2_GCJ02(wgs84Coord) {
		function outOfChina(lng, lat) {
			if (lng < 72.004 || lng > 137.8347) {
				return true;
			}
			if (lat < 0.8293 || lat > 55.8271) {
				return true;
			}
			return false;
			}
		  	var lng = parseFloat(wgs84Coord[0]);
			var lat = parseFloat(wgs84Coord[1]);

			var a = 6378245.0;
			var ee = 0.00669342162296594323;

			var transformLat = function(x, y) {
				var ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
				ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
				ret += (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
				ret += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
				return ret;
			};

			var transformLng = function(x, y) {
				var ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
				ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
				ret += (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
				ret += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0;
				return ret;
			};

			if (outOfChina(lng, lat)) {
				return [lng, lat];
			}

			var dLat = transformLat(lng - 105.0, lat - 35.0);
			var dLng = transformLng(lng - 105.0, lat - 35.0);
			var radLat = lat / 180.0 * Math.PI;
			var magic = Math.sin(radLat);
			magic = 1 - ee * magic * magic;
			var sqrtMagic = Math.sqrt(magic);
			dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * Math.PI);
			dLng = (dLng * 180.0) / (a / sqrtMagic * Math.cos(radLat) * Math.PI);

			var mgLat = lat + dLat;
			var mgLng = lng + dLng;

			return [mgLng, mgLat];
	},
	// 获取当前年月日
	 getCurrentDate() {
				const currentDate = new Date();
				const year = currentDate.getFullYear();
				const month = (currentDate.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以要加1
				const day = currentDate.getDate().toString().padStart(2, '0');
				return `${year}${month}${day}`;
	},
	// 时间格式修改
	 getDateString(dateString ) {
		const year = dateString.substring(0, 4);
		const month = dateString.substring(4, 6);
		const day = dateString.substring(6, 8);
		const hour = dateString.substring(8, 10);
		const minute = dateString.substring(10, 12);
		const second = dateString.substring(12, 14);
		const millisecond = dateString.substring(14);

		const formattedDate = `${year}-${month}-${day} ${hour}:${minute}:${second}.${millisecond}`;
		return formattedDate
	},
	// 获取雷达设备信息
	async 	getDerviceMsg() {
		let timer  = this.getCurrentDate()
		//   let url = `/api/v1/param?refresh_token=${this.token}&timer=${timer}&Param_1=1&Param_2=1&Param_3=1&Param_4=1&Param_5=1&Param_6=1&Param_7=1&Param_8=1&Param_11=1&Param_12=1&Param_21=1&Param_22=1&Param_23=1&Param_28=1&Param_29=1` ;
		let url = `/api/v1/param?refresh_token=${this.token}&timer=${timer}&Type=2` ;
		 try {
			const res = await this.$http.get(url)
			const data =  res.data.data.data
			// let  flattenedObject =  data.reduce((acc, curr, index) => {
			// 	Object.assign(acc, curr);
			// 	return acc;
			// }, {});
			this.centerPoint =this.WGS84_2_GCJ02(  [data[1].Longitude,data[1].Latitude])

		  } catch (error) {
			console.error("请求数据时出错：", error);
		}
    },
	// 初始化socket连接
	initSocket() {
		if (this.socketTask) {
			this.socketTask.close();
		}
		let socketUrl = uni.getStorageSync("radarIP")
		? "ws://" + uni.getStorageSync("radarIP") + ":22504"
		: "ws://192.168.0.182:22504";
		this.socketTask = uni.connectSocket({
			url: socketUrl,
			success(res) {
				console.log('WebSocket 连接成功', res);
			},
			fail(err) {
				this.msg('服务器连接失败')
				this.reconnect(); // 重新连接
			}
		})

		this.socketTask.onOpen(res => {
			this.socketOpen = true
			this.reconnectNum = 3
			// 将16进制字符串转换为字节数组
			const hexString = 'aa aa aa aa aa aa aa aa aa aa';
			const byteArray = hexString.match(/.{1,2}/g).map(byte => parseInt(byte, 16));
			const data1 = new Uint8Array(byteArray);
			this.socketTask.send({
					data: JSON.stringify({
					time: Math.floor(Date.now()),
				}),
				success: () => {
					// console.log('验证成功');
				},
				fail: (err) => {
					console.error('消息发送失败', err);
				}
			});
			console.log('socket连接已打开');
		});
		this.socketTask.onMessage(message => {
			let data = JSON.parse(message.data)
			if(data.Radar){
				this.SiteNum = data.Radar.SiteNum
				this.manyPersonWays(data.Radar.Content)
				// console.log(data.Radar.Content,'接受的数据1');
			}

		})
		this.socketTask.onClose(res => {
			console.log('连接关闭')
			this.reconnect(); // 重新连接
		})
		this.socketTask.onError(err => {
			console.log('连接错误', err)
			// this.reconnect(); // 重新连接
		})
	},
	//重新连接
	reconnect() {
		this.socketTask = null
		this.socketOpen = false
		if (this.reconnectNum <= 1) {
			return
		}
		if (this.reconnectTimer) {
			clearTimeout(this.reconnectTimer); // 清除旧的定时器
			this.reconnectTimer = null
		}
		console.log(this.reconnectDelay / 1000 + '秒后尝试重新连接');
		this.reconnectTimer = setTimeout(() => {
			this.reconnectNum--
			this.initSocket(); // 重新初始化 WebSocket 连接
		}, this.reconnectDelay); // 延迟 3 秒后尝试重新连接
	},
	getTrackType(type){
		return{
		 0:'普通航迹',
		 1:'两个航迹的融合航迹',
		 2:'无源和雷达航迹的融合航迹',
		}[type] || '其他'
	},
	getMapDataFromCache() {
	  const A_MAP_KEY = "1f520f629a5d77331f39101e3ba2ca7e"; // 地图key
      const mapDataUrl = `https://webapi.amap.com/maps?key=${A_MAP_KEY}`;
      // 检查浏览器是否支持 Service Worker 和缓存 API
      if ('serviceWorker' in navigator && 'caches' in window) {
        navigator.serviceWorker.ready
          .then(registration => {
            return caches.match(mapDataUrl)
              .then(response => {
                if (response) {
                  return response.json();
                } else {
                  throw new Error('Map data not found in cache');
                }
              })
              .then(mapData => {
                // 获取到地图数据后更新组件的数据
                this.mapData = mapData;
              })
              .catch(error => {
                console.error('Error getting map data from cache:', error);
              });
          })
          .catch(error => {
            console.error('Service Worker registration failed:', error);
          });
      } else {
        console.error('Service Worker or Cache API is not supported.');
      }
  	},
	// 清除地图上的所有刻度
	clearMapCircles() {
		if (this.circles && this.circles.length > 0) {
			this.circles.forEach(circle => {
				circle.setMap(null); // 将刻度从地图上移除
			});
			this.circles = []; // 清空数组
		}
	},
	// 目标消息弹窗
	getMsgList(){
		// 列表信息弹窗
			this.title = '目标列表'
			this.modalName ='bottomModal'
			this.showFlag = 0
	},
	//地图控件
	getControl(item){
		if (item.name === '刷新') {
			uni.showLoading({
				title: '刷新中...',
				mask: true
			});
			// 清除地图上的所有 marker
				this.markers&&this.markers.forEach(marker => marker.setMap(null));
				this.markers = [];
				// 清除地图上的所有 polyline
				this.polyLines&&this.polyLines.forEach(polyline => polyline.setMap(null));
				this.polyLines = [];
				// 清除地图
				this.map.clearMap()
				// 隐藏加载提示
				for(let i = 0;i<this.circles.length;i++){
					const circle = this.circles[i]
					if(circle){
						this.map.add(circle)
					}
					if(this.centerMarker1){
					this.map.add(this.centerMarker1)
					}
				}
			setTimeout(() => {
				uni.hideLoading();
			}, 1000);
			return
		}else if (item.name=='图层') {
			this.showFlag = 3
		}else{
			if( item.name == '列表'){
				this.title = '目标列表'
				this.showFlag = 0
			}
			if( item.name == '站点'){
				this.radarName = uni.getStorageSync('radarName') || this.radarName
    			this.radarIP = uni.getStorageSync('radarIP') || this.radarIP
				this.map.setCenter(this.centerPoint);
				this.showFlag = 1
			}
			if( item.name == '设置'){
			this.showFlag = 4
		}
		}
		this.modalName ='bottomModal'
		this.title = item.name
	},

	// 地图相关配置
	handleSetMap(data){
		const _this =this
		_this.clearMapCircles();
		if(data.modelLocalData.length>0){
			data.modelLocalData.forEach(item => {
			var circle = new AMap.Circle({
				map: _this.map,
				center: _this.centerPoint, // 圆心位置
				radius: item, // 半径 单位:米
				strokeColor: "#1a61d3", // 线颜色
				strokeOpacity: 1, // 线透明度
				strokeWeight: 2, // 线粗细度
				fillColor: "#d3e3fd", // 填充颜色
				fillOpacity: 0.1, // 填充透明度
			});
			_this.circles.push(circle);
		});
		}
		data.targetSetData.includes("pId")?_this.showpId =true:_this.showpId =false
		data.targetSetData.includes("position")?_this.showPosition =true:_this.showPosition =false
		_this.showDuFenMiao =data.latChangeData
		_this.modalName =null
},
	// 切换图层
	changeMap(type){
		let base_url = "http://localhost:3000";
		//   let base_url = "http://192.168.10.99:3000";
		// 创建一个默认的图层组件
		const defaultLayer  = [new AMap.TileLayer({
			getTileUrl: function (x, y, z) {
				return `${base_url}/city/${z}/${x}/${y}.jpg`;
			},
			opacity: 1,
			zIndex: 99,
		})]
		// 创建一个卫星图图层组件
		// let satelliteLayer = new AMap.TileLayer.Satellite();
		const satelliteLayer  = [new AMap.TileLayer({
			getTileUrl: function (x, y, z) {
				return `${base_url}/satellite/${z}/${x}/${y}.jpg`;
			},
			opacity: 1,
			zIndex: 99,
		})]
		// 切换图层
		if(type=='city'){
			//获取地图图层数据
			this.map.add(defaultLayer)
			// this.map.setLayers([defaultLayer]); // 切换回默认图层
		}else{
			this.map.add(satelliteLayer)
			// this.map.setLayers([satelliteLayer]); // 切换到卫星图图层
		}
	},
	hideModal(){
		this.modalData = null
		this.modalName = null
	},
	//初始化地图
	initAmap() {
		// todo 这里的baseurl 是瓦片地图的图层 根据服务器来 后面要动态获取服务器的地址
		let base_url = "http://localhost:3000";
		// let base_url = "http://192.168.10.99:3000";
		const customLayer  = [new AMap.TileLayer({
			getTileUrl: function (x, y, z) {
				return `${base_url}/city/${z}/${x}/${y}.jpg`;
			},
			opacity: 1,
			zIndex: 99,
		})]
		this.map = new AMap.Map("container", {
			zoom: 12,
			resizeEnable: true,
			defaultCursor: 'pointer',
			showLabel: true,  //是否显示文字标注
			center: this.centerPoint ,
			scrollWheel: true,
			 viewMode: '3D', //显示罗盘 就需要3D地图了
       		 pitch: 0,
			 layers: customLayer,
		});
		this.map.add(customLayer)
		AMap.plugin(
		[
			"AMap.ToolBar",
			"AMap.Scale",
			'AMap.ControlBar'
		//   "AMap.MapType",
		],
		);
		// 创建中心点位标记
		this.centerMarker1 = new AMap.Marker({
			position:  this.centerPoint, // 设置标记的经纬度位置
			map: this.map, // 设置标记所在的地图实例
			icon: new AMap.Icon({
				size: new AMap.Size(32, 32), // 设置图标大小
				image: "/static/star2.png", // 设置图标的图片地址
				imageSize: new AMap.Size(32, 32), // 图片实际大小
				anchor: new AMap.Pixel(16, 16) // 设置锚点为图标中心（32x32的一半）
			})
		});
		// 添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
		this.map.addControl(new AMap.ToolBar());
		// 添加比例尺控件，展示地图在当前层级和纬度下的比例尺
		// this.map.addControl(new AMap.Scale());
		// var compass = new AMap.ControlBar({
		// 	showControlButton: true,
		// 	rotateWhenDown: false,
		// 	position: {
		// 		top: '10px',
		// 	},
		// });
		// this.map.addControl(compass); //todo会影响性能
		// this.map.on('rotate', (event)=> {
		// 	// 监听地图旋转的角度 动态设置marker的角度
		// 		for (let i = 0; i < this.markers.length; i++) {
		// 			if(this.markers[i] && this.markers[i].Course){
		// 				let angle = Number(event.rotation) + Number(this.markers[i].Course)
		// 				this.markers[i].setRotation(angle);
		// 			}
		// 		};
		// });

		},
	getType(type){
			return{
			0:'大船',
			1:'中型船',
			2:'小船',
			10:'行人',
			30:'汽车',
			20:'无人机',
			'-1':'未知',
			}[type] || '未知'
	},
	// 添加文本信息框
	addText(item,pos3){
			if(this.textLable){
				this.map.remove(this.textLable);
				this.textLable =null
			}
			// 添加信息窗体
			var infoContent = "";
			if (this.showPosition && this.showpId) {
				infoContent = `<div style="text-align:left;" >批号：${item.BatchNumber}</div><div style="text-align:left;" >方位：${Number(item.Azimuth).toFixed(2)}  °</div>`;
			} else if (this.showPosition && !this.showpId) {
				infoContent = `<div style="text-align:left;" >方位：${Number(item.Azimuth).toFixed(2)} °</div>`;
			} else if (!this.showPosition && this.showpId) {
				infoContent = `<div style="text-align:left;" >批号：${item.BatchNumber}</div>`;
			} else {
				infoContent = "";
			}
			this.textLable =  new AMap.Text({
				id:item.BatchNumber,
				Azimuth:item.BatchNumber,
				offset: new AMap.Pixel(60, -55),
				text: infoContent,  // 标签显示的文本内容
				position: pos3 // 标签显示的位置，经纬度坐标
			});
			this.map.add(this.textLable);

			this.map.setCenter(pos3)

				// 监听文本标签的点击事件
			this.textLable.on('click', ()=> {
				// 关闭（移除）文本标签
				this.map.remove(this.textLable);
			});
	},
	// 更新模态框数据的函数
	updateModalData(itemData,marker) {
		// 经纬度转度分秒
		function decimalToDMS(decimal) {
			var degrees = Math.floor(decimal);
			var minutes = Math.floor((decimal - degrees) * 60);
			var seconds = ((decimal - degrees - minutes / 60) * 3600).toFixed(2);
			return degrees + "° " + minutes + "' " + seconds + '"';
		}
		this.modalData = [
			{ name: '批       号', value: itemData.BatchNumber },
			// { name: '频       段', value: 'xxxx' },
			{ name: '距       离', value:   Number(itemData.Distance).toFixed(2) + 'm'},
			{ name: '类       别', value: this.getType(itemData.Type) },
			{ name: '方       位', value: Number(itemData.Azimuth).toFixed(2) + '°'},
			{ name: '速       度', value:  Number(itemData.RadialVelocity).toFixed(2) + 'm/s'},
			{ name: '幅       度', value: itemData.Amplitude },
			{ name: '经       度', value:marker.showDuFenMiao== 'du'?decimalToDMS(marker.getPosition().lng):marker.getPosition().lng }, // 实时经度
			{ name: '纬       度', value:marker.showDuFenMiao== 'du'?decimalToDMS(marker.getPosition().lat):marker.getPosition().lat },
			// { name: '时       间', value: itemData.Time },
		];
	},
	// 动态控制目标列表表头显示
	handCheck(list){
		this.showList={}
			for (let j = 0; j < list.length; j++) {
				if (list[j].check) {
					this.showList[list[j].label] = ''
				}
		}
	},
	//多目标点实时
	manyPersonWays(points) {
		if(!this.map) return
		const _this =this
		const map =_this.map
		const markerMap = new Map();
    	_this.markers.forEach(marker => markerMap.set(marker.w.id, marker));
		_this.messageNum = _this.markers.length
		var colors = [
				'#3366FF', '#FF0000', '#00FF00', '#495ac5', '#FF00FF', '#FF00FF',
				"rgb(0,0,128)",
				"rgb(200,84,128)",
				"rgb(255,165,0)",
				"rgb(0,128,128)",
				"rgb(0,0,255)",
				"rgb(255,192,203)",
				"rgb(128,0,128)",
				"rgb(128,0,0)",
				"rgb(0,0,0)",
				"rgb(165,42,42)",
				"rgb(0,0,139)",
				"rgb(0,139,139)",
				"rgb(84,84,84)",
				"rgb(139,0,139)",
				"rgb(85,107,47)",
				"rgb(255,140,0)",
				"rgb(153,50,204)",
				"rgb(233,150,122)",
				"rgb(148,0,211)",
				"rgb(75,120,130)",
				"rgb(84,84,220)",
				"rgb(173,216,230)",
				"rgb(144,0,144)",
				"rgb(211,0,211)",
				"rgb(255,182,193)",
				"rgb(128,0,255)",
			];
		points.forEach((item,index)=>{

			const batchNumber = item.BatchNumber;
			 let existingMarker = markerMap.get(batchNumber);
			//根据动态showList的值来控制要显示的字段
			_this.processedMarkers = _this.markers.map(item => {
				let processedItem = {};
				Object.keys(_this.showList).forEach(key => {
					processedItem[key] = item[key];
				});
				return processedItem;
			});
			// 如果标记已创建，则更新位置
			if (existingMarker) {
				let lastPosition = existingMarker.getPosition();
				function startTimer(marker) {
					return function() {
						var currentPosition = marker.getPosition();
						if (currentPosition.equals(lastPosition)) {
							clearMarkerAndPolyline(marker.w.id);
						} else {
							lastPosition = currentPosition;
							setTimeout(startTimer(marker), 10000);
						}
					};
				}
				setTimeout(startTimer(existingMarker),10000);
				updateExistingMarker(existingMarker, item);
			} else {
				// 如果未创建的就新建一个marker
				createNewMarker(item);
			}
			 function updateExistingMarker(marker, item) {
				if (item.Exist !== '1') {
					clearMarkerAndPolyline(marker.w.id);
				} else {
					 // 设置目标物的动态数据
					existingMarker.BatchNumber= item.BatchNumber,
					existingMarker.angle= item.Course,
					existingMarker.Distance= item.Distance,
					existingMarker.Azimuth= item.Azimuth,
					existingMarker.Amplitude= item.Amplitude,
					existingMarker.Type= item.Type,
					existingMarker.Speed= item.Speed,
					existingMarker.Longitude= item.Longitude,
					existingMarker.Latitude= item.Latitude,

					existingMarker.Altitude= item.Altitude,
					existingMarker.Time= item.Time,
					existingMarker.Course= item.Course,
					existingMarker.Elevation= item.Elevation,
					existingMarker.Noise= item.Noise,
					existingMarker.RadialVelocity= item.RadialVelocity;
					// 修改定位信息
					let pos3 = _this.WGS84_2_GCJ02([item.Longitude, item.Latitude]);
					existingMarker.setPosition(pos3);
					// 设置目标物的航向
					existingMarker.setRotation(Number(item.Course));
					updatePolylinePath(existingMarker);
					// 添加标记点点击事件监听器
					existingMarker.on("click", function (e) {
						if (existingMarker.CLASS_NAME === "AMap.Marker" && existingMarker.w.id === item.BatchNumber) {
							var marker = e.target || existingMarker;
							_this.isMoving = true;
							// 用户相关配置放到marker
							_this.markerId = marker.w.id;  // markerId 可用来显示列表是否高亮
							marker.active = true  //用来标记列表当前点击的数据
							marker.showpId = _this.showpId;

							marker.showPosition = _this.showPosition;
							marker.showDuFenMiao = _this.showDuFenMiao
							// 打开模态框
							if(_this.msgFlag){
								_this.title = `目标ID：${marker.w.id}`;
								_this.modalName = "bottomModal";
								_this.showFlag = 2;
							}

						}
						_this.addText(item,pos3)
					});
					if( existingMarker.w.id === _this.markerId && _this.isMoving){
						existingMarker.moving = function(item){
							// 添加显示信息
							var newPosition = existingMarker.getPosition();
							// 将标签移动到新位置
							if(_this.textLable){
								// 更新信息窗体
								var newTextContent = "";
								if (_this.showPosition && _this.showpId) {
									newTextContent = `<div style="text-align:left;" >批号：${item.BatchNumber}</div><div style="text-align:left;" >方位：${Number(item.Azimuth).toFixed(2)}  °</div>`;
								} else if (_this.showPosition && !_this.showpId) {
									newTextContent = `<div style="text-align:left;" >方位：${Number(item.Azimuth).toFixed(2)} °</div>`;
								} else if (!_this.showPosition && _this.showpId) {
									newTextContent = `<div style="text-align:left;" >批号：${item.BatchNumber}</div>`;
								} else {
									newTextContent = "";
								}
								_this.textLable.setText(newTextContent);
								_this.textLable.setPosition(newPosition);
							}
							if(_this.msgFlag){
								_this.updateModalData(item, existingMarker);
							}
						}
						existingMarker.moving(item);
					}
				}
			}

		})
		function createNewMarker(item) {
			const initialStatus = Number(item.Type); // 初始状态
			const num = Math.floor(Math.random() * 30) + 1;
			const marker = new AMap.Marker({
				id: item.BatchNumber,
				map: map,
				icon: getIconUrl(initialStatus),
				offset: new AMap.Pixel(-22, -35),
				status: initialStatus,
				Exist: item.Exist,
				color: colors[num],
				angle:0
			});
			_this.ids.push(item.BatchNumber);
			_this.markers.push(marker);
			markerMap.set(item.BatchNumber, marker);

			let pos2 = _this.WGS84_2_GCJ02([item.Longitude, item.Latitude]);
			marker.setPosition(pos2);
		}
		function clearMarkerAndPolyline(id) {
				clearMarker(id);
				clearPolyline(id);
				_this.ids.splice(_this.ids.indexOf(id), 1);

			}
		// 根据状态获取图标 URL
		function getIconUrl(status) {
			switch (status) {
				case 10:
					return 'static/people1.png'; // 人物 URL
				case 30:
					return 'static/car.png'; //  汽车URL
				case 20:
					return 'static/fly.png'; // 飞行物 URL
				default:
					return 'static/fly.png'; // 默认图标 URL
			}
		}
		// 清除折线
		function clearPolyline1(polyline) {
			if (polyline) {
				polyline.setMap(null); // 从地图上移除折线
			}
		}
		// 绘制标记点的路线并指定颜色
		function updatePolylinePath(marker) {
			if(!marker)return
			  // 清除该标记点对应的折线
    			clearPolyline1(marker.polyline);
				var path = []; // 折线路径数组
				if (marker.previousPosition) {
					// 如果存在上一个位置，则绘制从上一个位置到当前位置的折线
					path.push([marker.previousPosition.lng,marker.previousPosition.lat]); // 上一个位置
					path.push(marker.getPosition()); // 当前位置

					// 在路径数组中添加起点和终点
					var startPoint = path[0];
					var endPoint = path[path.length - 1];
					path.unshift(startPoint); // 添加起点
					path.push(endPoint); // 添加终点

					// 创建折线对象，并指定颜色和箭头标记
					var polyline = new AMap.Polyline({
						map: map,
						id:marker.w.id,
						Exist:marker.w.Exist,
						path: path, // 折线路径
						strokeColor: marker.w.color, // 指定颜色
						strokeOpacity: 1,
						strokeWeight: 3,
						strokeStyle: 'solid',
						strokeDasharray: [10, 5],  // 线样式为虚线
						showDir: true // 显示箭头标记
					});

					// 将折线对象添加到数组中
					_this.polylines.push(polyline);
				}
				// 更新标记点的上一个位置
				marker.previousPosition = marker.getPosition();
		}
		// 删除marker
		function clearMarker(id){
			const idx = parseInt(id, 10);
			_this.markers.forEach((marker, i) => {
				const markerId = marker.w.id;
				const markerExist = marker.w.Exist;

				if (marker === idx || markerId === id || markerExist !== '1') {
					marker.setMap(null);
					_this.markers.splice(i, 1);
					_this.processedMarkers.splice(i, 1);
				}
			});

			if (_this.textLable && id === _this.textLable.w.id) {
				_this.map.remove(_this.textLable);
				_this.textLable = null;
			}
		}
		// 删除轨迹
		function clearPolyline(id){
				for (let i = 0; i < _this.polylines.length; i++) {
					const polyline = _this.polylines[i];
					if (polyline.w.id === id || polyline.w.Exist !== '1') {
						_this.polylines.splice(i, 1); // 从数组中移除折线对象
						polyline.setMap(null); // 从地图上移除折线
						i--;
					}
				}

		}

	}
	},

};
</script>

<style scoped>
td,
tr {
  border: 1px solid #ccc;
}
.device_box {
  position: absolute;
  top: 50px;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 20px;
  background-color: #999999;
  width: 300px;
  height: 50px;
  color: #fff;
  font-weight: 700;
  text-align: center;
  border-radius: 5px;
  /* border: 1px solid #ccc; */
  line-height: 50px;
  /* animation: msgbeat 1s infinite; */
}
.home {
  position: relative;
}
.cu-modal {
  z-index: 9999;
  background-color: transparent;
  /* height: 35%; */
  position: fixed !important;
  left: 0 !important;
  top: auto;
}

css .notification {
  display: inline-block;
  position: relative;
}

.heartbeat {
  width: 40px;
  height: 40px;
  background-color: #ff4835;
  border-radius: 50%;
  position: absolute;
  top: 10%;
  left: 6%;
  transform: translate(-50%, -50%);
  animation: heartbeat 1s infinite;
  line-height: 40px;
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  color: #fff;
  z-index: 9999;
}

.messageNum {
  width: 40px;
  height: 40px;
  background-color: #4095e5;
  border-radius: 50%;
  position: absolute;
  top: 10%;
  left: 6%;
  line-height: 40px;
  text-align: center;
  font-size: 20px;
  font-weight: 700;
  color: #fff;
}

@keyframes heartbeat {
  0% {
    transform: scale(1);
    opacity: 1;
  }

  50% {
    transform: scale(1.2);
    opacity: 0.7;
  }

  100% {
    transform: scale(1);
    opacity: 1;
  }
}
@keyframes msgbeat {
  0% {
    color: #fff;
    opacity: 0.1;
  }

  50% {
    opacity: 1;
    color: red;
  }

  100% {
    color: #fff;
    opacity: 0.1;
  }
}

.cu-list.grid > .cu-item {
  padding: 0px 0px;
}

.line2-icon {
  width: 60px;
  height: 60px;
}

#container {
  height: 100vh;
  width: 100%;
}

::v-deep .amap-touch-toolbar .amap-zoomcontrol {
  position: absolute;
  bottom: 250px !important;
}
::v-deep .amap-controlbar {
  right: 10px !important;
  /* bottom: 300px !important; */
}
::v-deep .amap-marker {
  z-index: 10000 !important;
}
/*  amap-touch-toolbar */
::v-deep .amap-toolbar {
  bottom: 140px !important;
}
.contron_box {
  width: 32px;
  /* height: 100px; */
  position: fixed;
  right: 20px;
  top: 220px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  text-align: center;
  overflow: hidden;
  background-color: rgba(242, 242, 242, 0.9);
  /* 调整透明度为 0.5 */
  border-radius: 10px;
  padding: 10px 0 0 0;
}

.c_items {
  width: 32px;
  height: 40px;
  font-size: 12px;
  color: #000;
  font-weight: 500;
}
.active {
  background-color: #ccc;
}
tr:hover {
  background-color: #ccc;
}
</style>
